package com.ebelter.bpm.activitys;
import android.bluetooth.BluetoothDevice;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ebelter.bpm.R;
import com.ebelter.bpm.models.update.Updater;
import com.ebelter.btcomlib.bases.activity.BaseHandleActivity;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.common.IOrder;
import com.ebelter.btcomlib.models.bluetooth.base.BlueScan;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScanCallback;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.BPMConstant;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.BpmManager;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.bean.BpmMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.interfaces.BPMMeasureCallback;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.GetBloodPressureData1;
import com.ebelter.btcomlib.models.upload.UploadDataUtils;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.ChartView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BPMMainActivity extends BaseHandleActivity implements IOrder {

    public static final String TAG = "BPMMainActivity";

    private static final int WHAT_SCAN_BLUETOOTH = 1;//扫描蓝牙
    private static final int WHAT_CHECK_HEART = 2;//检测心跳


    //private LinearLayout nopairedtiply_root_ll;//绑定提示根布局


    private BpmManager mBpmManager;
    private BlueScan mBlueScan;
    private UploadDataUtils mUploadDataUtils;

    private Updater mUpdater;
    private ImageView connectstation_iv;
    private boolean isResume;

    private TextView today_tv;//今天文本

    private TextView title1_tv;//测量状态文本
    private TextView title2_tv;//收缩压、舒张压文本
    private TextView title3_tv;//脉搏文本

    private ChartView chartview_ss_sz;
    private ChartView chartview_maibo;


    @Override
    protected void handleMsg(Message msg) {
        if (msg.what == WHAT_SCAN_BLUETOOTH){//开始扫描设备
            startScan();
        }else if(msg.what==WHAT_CHECK_HEART){//检测心跳包
            sendEmptyMessageDelayed(WHAT_CHECK_HEART,5000);
            checkHeart();
        }

    }

    //检测心跳包
    private void checkHeart() {

        LogUtils.i(TAG,"----------------checkHeart()");

        if (mBpmManager==null)return;

        if (mBpmManager.isConnect()){
            LogUtils.i(TAG,"--checkHeart--设备已经连接,无需重新扫描连接");
            return;
        }
        if (mBlueScan==null) return;

        if (mBlueScan.isScaningFlag){
            LogUtils.i(TAG,"--checkHeart--App已经在扫描中,无需重新扫描连接");
            return;
        }

        startScan();



    }

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_bpm_main;
    }

    @Override
    protected void initView() {
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
        }

        FV();
        mUpdater=new Updater();
        mUpdater.checkVersion(this,false,true);//检测版本更新
        resultTvToEmpty();

        today_tv.setText(getString_(R.string.today)+"（"+TimeUtils.formatDateStampString0(getApplication(),System.currentTimeMillis())+")");

    }

    @Override
    protected void initData() {
        mBpmManager = new BpmManager(this);


        if (!mBpmManager.isSupportBluetooth()){
            ToastUtil.show(R.string.no_support_bluetooth_tip);
        }else if (!mBpmManager.isBluetoothOpen()){
            ToastUtil.show(R.string.no_open_bluetooth_tip);
        }




        mBlueScan = new BlueScan(this);

        mUploadDataUtils = new UploadDataUtils(this);

        mUploadDataUtils.startCheckDB();

        setListeners();

      //  getTodayData();


    }

    private void setListeners() {

        //nopairedtiply_root_ll.setOnClickListener(this);
        mBlueScan.setScanCallback(new IScanCallback() {
            @Override
            public void beforeScan() {}

            @Override
            public void scanOneDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
                LogUtils.i(TAG,"扫描到设备：name="+device.getName()+"---address="+device.getAddress());
                if (mBpmManager!=null&&(TextUtils.equals(device.getName(), BPMConstant.BPM_NAME)||TextUtils.equals(device.getName(), BPMConstant.BPM_NAME2))){
                    mBpmManager.connectDevice(device.getAddress());
                }

            }

            @Override
            public void overScan() {}
        });


        mBpmManager.setBlueConnectStationCallback(mIConnectStationCallback);

        mBpmManager.setBpmMeasureCallback(new BPMMeasureCallback() {
            @Override
            public void dynamicSystolicPressure(int value) {
                //测量中的动态血压值
                LogUtils.i(TAG,"---动态血压值--dynamicSystolicPressure() = "+value);
                //ViewUtils.setTextViewStr(title2_tv,value+"/000");
                ViewUtils.setTextViewStr(title2_tv,value + "/000");
            }
            /**测量错误
             errorType=1 传感器震荡异常,设备LCD显示ERR1
             errorType=2 检测不到足够的心跳或算不出血压，设备LCD显示ERR2
             errorType=3 测量结果异常，设备LCD显示ERR3
             errorType=4 测量结果异常或压力超过上限，设备LCD显示ERR H
             errorType=5 袖带过松或漏气(10秒内加压不到30mmHg)，设备LCD显示ERR U
             errorType=6 电池电量过低，提示用户更换电池, LCD显示
             */
            @Override
            public void measureError(String conName,int errorType) {
                //测量错误
                LogUtils.i(TAG,"---错误码--measureError() = " + errorType+"---conName="+conName);

                if (TextUtils.equals(BPMConstant.BPM_NAME,conName)){
                    ToastUtil.show(BpmManager.getErrorInfoDesc(errorType));
                }else {
                    ToastUtil.show(BpmManager.getErrorInfoDesc2(errorType));
                }



            }

            @Override
            public void measureResult(BpmMesureResult mesureResult) {
                if (mesureResult==null) return;
                //测量结果
                LogUtils.i(TAG,"---测量结果--measureResult() = " + mesureResult.toString());

                if (mBpmManager!=null){
                    mBpmManager.sendReceiveSuccessACK();
                }
                ViewUtils.setTextViewStr(title2_tv,mesureResult.systolicPressure + "/" + mesureResult.diastolicPressure);
                ViewUtils.setTextViewStr(title3_tv,mesureResult.pulse + StringUtils.getResStr(R.string.cifen));
                ViewUtils.setTextViewStr(title1_tv,BpmManager.getMesureResultDesc(mesureResult.systolicPressure,mesureResult.diastolicPressure));

                if (mUploadDataUtils!=null){
                    long currentTime = System.currentTimeMillis();
                    if (currentTime-lastUploadDateTime<27000){
                        LogUtils.i(TAG,"数据上传时间间隔小于27秒被reture");
                    }else {
                        lastUploadDateTime=currentTime;
                        mesureResult.userID= UserSpUtil.readLong(Constants.IUser.USER_ID);
                        mUploadDataUtils.uploadBloodPressureDate(mesureResult,true);
                    }

                }


            }
        });

    }


    private long firstBackTime;

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstBackTime > 2000) {
            ToastUtil.show(R.string.Touch_again_to_exit);
            firstBackTime = secondTime;
        } else {
            System.exit(0);
        }
    }

    private long lastUploadDateTime;

    private void resultTvToEmpty(){
        ViewUtils.setTextViewStr(title1_tv,"——");
        ViewUtils.setTextViewStr(title2_tv,"000/000");
        ViewUtils.setTextViewStr(title3_tv,"00 "+getString(R.string.cifen));
    }

    //连接状态的回调器
    private IConnectStationCallback mIConnectStationCallback= new IConnectStationCallback() {
        @Override
        public void onConnected(ProductStyle productStyle,BluetoothDevice device) {
            LogUtils.i(TAG,"mIConnectStationCallback--连接成功---Name = "+device.getName()+"---Address = "+device.getAddress());

            if (isResume){ToastUtil.show(R.string.shblylj);}
            if(mBpmManager!=null){mBpmManager.setConnectName(device.getName());}

            if (connectstation_iv!=null)connectstation_iv.setImageResource(R.drawable.ic_connected);
        }

        @Override
        public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {

        }

        @Override
        public void onDisConnected(ProductStyle productStyle) {
            LogUtils.i(TAG,"mIConnectStationCallback--连接断开--准备重新扫描");
            if (isResume){ToastUtil.show(R.string.shblydk);}
           // resultTvToEmpty();
            //sendEmptyMessage(WHAT_SCAN_BLUETOOTH);//当断开连接的时候重新去扫描设备
            removeMessages(WHAT_CHECK_HEART);
            sendEmptyMessage(WHAT_CHECK_HEART);
            if (connectstation_iv!=null)connectstation_iv.setImageResource(R.drawable.ic_disconnected);
        }
    };

    private void FV() {

        today_tv = findViewById(R.id.today_tv);
        connectstation_iv = findViewById(R.id.connectstation_iv);

        title1_tv = findViewById(R.id.title1_tv);
        title2_tv = findViewById(R.id.title2_tv);
        title3_tv = findViewById(R.id.title3_tv);
        chartview_ss_sz = findViewById(R.id.chartview_ss_sz);
        chartview_maibo = findViewById(R.id.chartview_maibo);

    }



    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        removeMessages(WHAT_CHECK_HEART);
        sendEmptyMessage(WHAT_CHECK_HEART);

    }

    //获取今天的数据
    private void getTodayData() {

        LogUtils.i(TAG,"------------getTodayData()");

        String today = TimeUtils.getTodayZeroTime(0,true);
        String tomorrow = TimeUtils.getTodayZeroTime(1,true);


        NetUtils.getInstance().getTodayBloodPressureData(this, 500,today,tomorrow, new HttpResponse<GetBloodPressureData1>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetBloodPressureData1 getBloodPressureData1, String s) {

                if (!isRequestSuccess){
                    return;
                }
                LogUtils.i(TAG,"----getTodayData---"+getBloodPressureData1.toString());

                if (getBloodPressureData1.getResultCode()==0){
                    disCharView(getBloodPressureData1);
                }



            }
        });


    }

    //显示charView
    private void disCharView(GetBloodPressureData1 getBloodPressureData1) {



        if (getBloodPressureData1!=null&&getBloodPressureData1.getResultData()!=null
                &&getBloodPressureData1.getResultData().getData()!=null
                &&getBloodPressureData1.getResultData().getData().size()>0){


            //x轴坐标对应的数据
            List<String> oneXValue = new ArrayList<>();

            //y轴坐标对应的数据
            List<Integer> oneYValue = new ArrayList<>();
            //折线对应的数据
            Map<String, Integer> oneValue = new HashMap<>();
            Map<String, Integer> oneValue2 = new HashMap<>();
            Map<String, Integer> twoValue = new HashMap<>();

            int maxVaue=0;
            for (int i=0;i<getBloodPressureData1.getResultData().getData().size();i++){

                GetBloodPressureData1.ResultDataBean.DataBean bean=getBloodPressureData1.getResultData().getData().get(i);
                if (bean==null|| StringUtils.isEmpty(bean.getTestDate())){
                    continue;
                }

//                String disTime1=StringUtils.subString(bean.getTestDate(),5,10);
//             //   String disTime2=StringUtils.subString(bean.getTestDate(),11,16);
//                String disTime2=StringUtils.subString(bean.getTestDate(),10,16);
//             //   String disTime = disTime1+" "+disTime2;
//                String disTime = disTime1 + disTime2;
                String disTime = bean.getTestDate();

                int ss = bean.getSystolic();

                if (ss > maxVaue){
                    maxVaue = ss;
                }
                int sz = bean.getDiastolic();
                int mb = bean.getPulse();

                oneXValue.add(disTime);
                oneValue.put(disTime, ss);//60--240
                oneValue2.put(disTime, sz);//60--240
                twoValue.put(disTime, mb);//60--240

            }

            int h=7;
            if (maxVaue>0){
                h = maxVaue / 30 + 3;
            }
            for (int i = 0; i < h; i++) {//Y轴的刻度值
                oneYValue.add(i *30);
            }


            if (chartview_ss_sz!=null){
                chartview_ss_sz.isDisplayXDateFlag=false;
                chartview_ss_sz.setValue(oneValue,oneValue2,oneXValue,oneYValue);
            }

            if (chartview_maibo!=null){
                chartview_maibo.isDisplayXDateFlag = false;
                chartview_maibo.setValue(twoValue,null,oneXValue,oneYValue);
            }



        }




    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume =false;
        removeMessages(WHAT_CHECK_HEART);
    }

    //开始扫描设备
    private void startScan(){
        LogUtils.i(TAG,"开始扫描设备--startScan（）");
        if (mBlueScan!=null) mBlueScan.startScanBluetoothDevices();
    }

    //设置按钮被点击
    public void setting(View view){
        startActivity(BPM_SettingActivity.class);
    }





    //趋势
    public void trendClick(View view){
        startActivity(BPM_BloodPressureCurveActivity.class);

    }

    @Override
    protected boolean isOpenNetStationListener() {
        return true;
    }

    @Override
    protected void netStationChange(int netWorkState) {
        LogUtils.i(TAG,"接收到网络状态监听器--netWorkState = " + netWorkState);

        if (netWorkState!=-1){
            getTodayData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBlueScan != null){
            mBlueScan.exitScan();
            mBlueScan=null;
        }
        if (mUploadDataUtils != null){
            mUploadDataUtils.exit();
            mUploadDataUtils=null;
        }
        if (mBpmManager != null){
            mBpmManager.exit();
            mBpmManager=null;
        }
    }

    @Override
    public void cmd(int cmd, Object... objects) {
        LogUtils.i(TAG,"主界面收到cmd指令--cmd = "+cmd);
        if (cmd == UploadDataUtils.UPLOAD_DATA_SUCCESS){
            //表示上传工具上传数据成功 重新拉取一下今天的数据信息
            getTodayData();
        }
    }
}
